package com.mj.app.common_util.net;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.mj.app.common_util.util.HttpUtil;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

import static android.content.ContentValues.TAG;

/**
 * ========================================
 * *
 * title: HttpConnection
 * description:
 * *
 * Created by David Hogan on 2018/3/2.
 * ========================================
 */

public class HttpConnection <T extends ResponseBean>{

    private String urlPath;
    private PostBean postBean;
    private CallBack<T> callBack;
    private Class<T> responseClass;

    public HttpConnection(String urlPath, PostBean postBean, CallBack<T> callBack,
                          Class<T> responseClass) {
        this.urlPath = urlPath;
        this.postBean = postBean;
        this.callBack = callBack;
        this.responseClass = responseClass;
    }

    //发送JSON字符串 如果成功则返回成功标识。
    public String doJsonPost() {
        // HttpClient 6.0被抛弃了
        String result = "";
        String Json = postBean.getJson();

        BufferedReader reader = null;
        try {
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
            conn.setRequestProperty("accept","application/json");
            // 往服务器里面发送数据
            if (Json != null && !TextUtils.isEmpty(Json)) {
                byte[] writebytes = Json.getBytes();
                // 设置文件长度
                conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = conn.getOutputStream();
                outwritestream.write(Json.getBytes());
                outwritestream.flush();
                outwritestream.close();
                Log.i("health_conn-发送报文", "doJsonPost: "+Json);
            }
            if (conn.getResponseCode() == 200) {

                reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                result = reader.readLine();

                Log.i("health_conn-响应报文：",result);
                T t = new Gson().fromJson(result, responseClass);
                callBack.onSuccess(t);
            }else{
                callBack.onError("服务器链接异常");

                Log.i("health_conn-响应报文：","服务器链接异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
